package cn.yaoud.salus.oms.alarm.feishu;

import cn.yaoud.salus.oms.alarm.Alerter;
import cn.yaoud.salus.oms.alarm.feishu.bot.FeiShuRobotEnum;
import cn.yaoud.salus.oms.alarm.feishu.bot.ReportExceptionDto;
import cn.yaoud.salus.oms.alarm.util.StackTraceUtil;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;

/**
 * 通过飞书发送通知
 *
 * @author 唐彪
 */
public class FeiShuAlerter implements Alerter {
    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    /**
     * 当前应用名称
     */
    private String applicationName;
    private Executor executor;

    @Override
    public void info(String title, String msg) {
        Map<String, Object> params = new HashMap<>();
        params.put("title", title);
        params.put("time", formatter.format(LocalDateTime.now()));
        params.put("msg", msg);
        FeiShuRobotEnum.ALERTER.cardTemplate("AAqHBIclFVnJu", "1.0.0", params);
    }

    @Override
    public void report(Throwable t) {
        String stackTrace = StackTraceUtil.printStackTraceToString(t);
        ReportExceptionDto reportExceptionDto = new ReportExceptionDto();
        reportExceptionDto.setTitle("🔔" + applicationName + "发生异常，请关注！");
        reportExceptionDto.setBrief(String.format("%s:%s", t.getClass().getCanonicalName(), t.getMessage()));
        reportExceptionDto.setTime(formatter.format(LocalDateTime.now()));
        reportExceptionDto.setContent(stackTrace);
        if (Objects.nonNull(RequestContextHolder.getRequestAttributes())) {
            HttpServletRequest request =
                    ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            reportExceptionDto.setRequestUrl(String.format("%s %s", request.getMethod(), request.getRequestURI()));
        }
        executor.execute(() -> FeiShuRobotEnum.ALARM.reportException(reportExceptionDto));
    }

    public void setApplicationName(String applicationName) {
        this.applicationName = applicationName;
    }

    public void setExecutor(Executor executor) {
        this.executor = executor;
    }
}
